package Controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import object.ResetBox;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import DAO.AdminDao;
import DAO.AgentDao;
import DAO.BoxDao;
import DAO.BranchDao;
import DAO.CompanyDao;
import DAO.CourierDao;
import DAO.ExpenseDao;
import DAO.ExpressDao;
import DAO.GoodsDao;
import DAO.MessageResponseDao;
import DAO.ParcelDao;
import DAO.TerminalDao;
import DAO.UserDao;
import POJO.Agent;
import POJO.Box;
import POJO.BoxOrderList;
import POJO.CleaningBox;
import POJO.Company;
import POJO.Courier;
import POJO.Express;
import POJO.Goods;
import POJO.Parcel;
import POJO.Terminal;
import POJO.User;
import Thread.RequestNotifyThread;
import Utils.GenerateRandNumHelper;
import Utils.SendSMSHelper;
import Utils.TimeHelper;

@Controller
@RequestMapping(value = "auth")
public class AuthController {
	static Logger logger = Logger.getLogger(AuthController.class);
//	static int number = 1;
	@Autowired
	private TerminalDao terminalDao;
	@Autowired
	private CourierDao courierDao;
	@Autowired
	private ParcelDao parcelDao;
	@Autowired
	private BoxDao boxDao;
	@Autowired
	private AdminDao adminDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private CompanyDao companyDao;
	@Autowired
	private ExpressDao expressDao;
	@Autowired
	private GoodsDao goodsDao;
	@Autowired
	private AgentDao agentDao;
	@Autowired
	MessageResponseDao messageResponseDao;
	@Autowired
	ExpenseDao expenseDao;
	@Autowired
	BranchDao branchDao;

	@RequestMapping("terminal/login")
	@ResponseBody
	public Map<String, Object> TerminalLogin(
			@RequestParam(value = "devId", defaultValue = "-1") int devId,
			@RequestParam(value = "softVer", required = false) String softVer,
			@RequestParam(value = "hardVer", required = false) String hardVer,
			@RequestParam(value = "pwd", required = false) String pwd,
			@RequestParam(value = "peripheralStatus", defaultValue = "0") int peripheralStatus,
			@RequestParam(value = "peripheralSoftVer", defaultValue = "empty") String peripheralSoftVer,
			@RequestParam(value = "lock", defaultValue = "empty") String lock,
			@RequestParam(value = "check", defaultValue = "empty") String check,
			@RequestParam(value = "barcodeStatus", defaultValue = "0") String barcodeStatus,
			@RequestParam(value = "cardReadStatus", defaultValue = "0") String cardReadStatus,
			@RequestParam(value = "touchStatus", defaultValue = "0") String touchStatus,
			@RequestParam(value = "networkType", defaultValue = "0") String networkType,
			@RequestParam(value = "networkIP", defaultValue = "empty") String networkIP,
			@RequestParam(value = "simcardNum", defaultValue = "empty") String simcardNum,
			HttpSession httpSession, HttpServletRequest httpRequest) {

		HashMap<String, Object> response = new HashMap<String, Object>();
		if (devId == -1) {
			// 心跳包模式
			Terminal terminal = (Terminal) httpSession.getAttribute("terminal");
			ArrayList<Box> boxes = null;
			ArrayList<CleaningBox> cleaningBoxs = null;
			ArrayList<BoxOrderList> boxOderList = null;
			ArrayList<BoxOrderList> boxCancelOderList = null;
			ArrayList<Goods> timeOutGoodsList = null;
			ArrayList<ResetBox> resetGoodBoxs = null;
			ArrayList<ResetBox> resetParcelBoxs = null;
			if (terminal != null) {
				boxes = boxDao.returnForceOpenBoxes(terminal);
				if(TimeHelper.isNowLate(terminal.getLoginTime(), 1)){
					terminalDao.updateLoginTime(terminal);
				}
				if(terminal.getAgentID()==34){
					cleaningBoxs = boxDao.returnCleaningBox(terminal);
					boxOderList = goodsDao.getByTerminalIDAndRemark(terminal.getTerminalID(), "0");
					boxCancelOderList = goodsDao.getByTerminalIDAndRemark(terminal.getTerminalID(), "2");
					timeOutGoodsList = goodsDao.getTimeOutGoods(terminal.getTerminalID(), "0");
					resetGoodBoxs = goodsDao.getResetBox(terminal.getTerminalID(), "6");
					resetParcelBoxs = parcelDao.getResetBoxes(terminal.getTerminalID(), 3);
				}
				if (boxes != null) {
					// 有箱子需要强开
					for (Box b : boxes) {
						boxDao.updateForceOpenBoxStatus(terminal, b.getBoxSeq());
						b.setServerTime(new Timestamp(System.currentTimeMillis() / 1000));
					}
					response.put("result", "0");
					response.put("forceOpen", boxes);
					return response;
				}else if (cleaningBoxs != null) {
					// 有箱子需要清空
					for (CleaningBox c : cleaningBoxs) {
						boxDao.updateForceOpenBoxStatus(terminal, c.getBoxSeq());
					}
					response.put("result", "10");
					response.put("cleaningBox", cleaningBoxs);
					return response;
				} else if (boxOderList != null) {
					for (BoxOrderList b : boxOderList) {
						goodsDao.updateRemarkByOrderNo(b.getOrderNum(), "1");
						Goods goods = goodsDao.getGoodsByOrderNo(b
								.getOrderNum());
						if (TimeHelper.isNowLate(goods.getBookingTime())) {
							Agent agent = agentDao.getAgentById(goods
									.getAgentId());
							RequestNotifyThread rnt = new RequestNotifyThread();
							Long timestamp = System.currentTimeMillis() / 1000;

							rnt.setSign(agent.getSign(timestamp));
							rnt.setUrl(agent.getFeedbackUrl());
							rnt.setTimestamp(String.valueOf(timestamp));
							rnt.setFuncName("OrderStatusResult");
							rnt.setOrderNum(goods.getOrderNo());
							rnt.setOrderStatus("4");
							rnt.setSaveOpenCode(goods.getOpenCode());
							rnt.setBoxNum(String.valueOf(goods.getBoxNum()));
							rnt.setCancelTime(String.valueOf(goods
									.getDeadTime().getTime()/1000));
							Thread thread = new Thread(rnt);
							thread.start();
						}
					}
					response.put("result", "7");
					response.put("BoxOderList", boxOderList);
					return response;
				} else if (boxCancelOderList != null) {
					for (BoxOrderList b : boxCancelOderList) {
						goodsDao.updateRemarkByOrderNo(b.getOrderNum(), "3");
					}
					response.put("result", "8");
					response.put("BoxCancelOderList", boxCancelOderList);
					return response;
				} else if (timeOutGoodsList != null) {
					for (Goods goods : timeOutGoodsList) {
						goodsDao.updateRemarkByOrderNo(goods.getOrderNo(), "4");
					}
					response.put("result", "8");
					response.put("BoxCancelOderList", getList(timeOutGoodsList));
					return response;
				}else if (resetGoodBoxs != null) {
					for(ResetBox resetBox:resetGoodBoxs){
						goodsDao.updateRemarkByOrderNo(resetBox.getItemNum(), "7");
					}
					response.put("result", "11");
					response.put("resetBox", resetGoodBoxs);
					return response;
				} else if (resetParcelBoxs != null) {
					for(ResetBox resetBox:resetParcelBoxs){
						parcelDao.updateFlagByOrderNo(resetBox.getItemNum(), 4);
					}
					response.put("result", "11");
					response.put("resetBox", resetParcelBoxs);
					return response;
				} else {
					// 控制代码下发
					response = (HashMap<String, Object>) httpRequest
							.getServletContext().getAttribute(
									"terminal" + terminal.getTerminalID());
					if (response == null) {
						// 无任何消息
						response = new HashMap<String, Object>();
						response.put("result", "1");
					} else {
						if (response.containsKey("result")) {
							if (!response.get("result").equals("5")) {
								// 系统维护需要保持
								httpRequest
										.getServletContext()
										.removeAttribute(
												"terminal"
														+ terminal
																.getTerminalID());
							}
						}
					}
				}
			} else {
				// 未登录
				response.put("result", "9");
				response.put("errMsg", "terminal is null");
//				logger.info("[ERROR]terminal is null");
			}
		} else {
			Terminal terminal = (Terminal) httpRequest.getServletContext()
					.getAttribute("terminalCache" + devId + pwd);
			if (terminal == null) {
				terminal = terminalDao.valifiy(devId, pwd);
				if (terminal != null) {
//					logger.info("[WARN]miss hit terminal cache!");
					httpRequest.getServletContext().setAttribute(
							"terminalCache" + devId + pwd, terminal);
				} else {
					response.put("result", "1");
					return response;
				}
			}

			// TEST
			// terminal.print();
			// TEST

			terminal.sethVersion(hardVer);
			terminal.setsVersion(softVer);
			terminal.setPeripheralStatus(peripheralStatus);
			terminal.setPeripheralSoftVer(peripheralSoftVer);
			terminal.setLock(lock);
			terminal.setCheck(check);
			terminal.setBarcodeStatus(barcodeStatus);
			terminal.setCardReadStatus(cardReadStatus);
			terminal.setTouchStatus(touchStatus);
			terminal.setNetworkIP(networkIP);
			terminal.setNetworkType(networkType);
			terminal.setSimcardNum(simcardNum);
			terminalDao.updateVersion(terminal);
			httpSession.setAttribute("terminal", terminal);
			response.put("result", "0");
			response.put("terminalId", terminal.getTerminalID());
			response.put("adminPwd", terminal.getAdminPwd());
			response.put("costType", terminal.getCostType());
			response.put("standardCost", terminal.getStandardCost());
			response.put("standardDuration", terminal.getStandardDuration());
			response.put("increaseCost", terminal.getIncreaseCost());
			response.put("increaseDuration", terminal.getIncreaseDuration());

			// 防止终端断线后，再次连入系统时，开箱数据为过期，导致开箱错误
			// Bug fix Begin
//			ArrayList<Box> boxes = boxDao.returnForceOpenBoxes(terminal);
//			if (boxes != null) {
//				// 有箱子需要强开
//				for (Box b : boxes) {
//					boxDao.updateForceOpenBoxStatus(terminal, b.getBoxSeq());
//				}
//			}

			HashMap<String, Object> status = (HashMap<String, Object>) httpRequest
					.getServletContext().getAttribute(
							"terminal" + terminal.getTerminalID());
			if (status != null) {
				if (status.containsKey("result")) {
					httpRequest.getServletContext().removeAttribute(
							"terminal" + terminal.getTerminalID());
				}
			}
			// Bug fix End 2013-12-20 21:32:19
		}
		return response;
	}

	/**
	 * 过滤队列
	 * 
	 * @param goods
	 * @return
	 */
	private ArrayList<BoxOrderList> getList(ArrayList<Goods> goods) {
		ArrayList<BoxOrderList> boxOrderLists = new ArrayList<BoxOrderList>();
		for (Goods g : goods) {
			BoxOrderList list = new BoxOrderList();
			list.setBoxNum(String.valueOf(g.getBoxNum()));
			list.setMobileNum(g.getCourierMobileNum());
			list.setOpenCode(g.getOpenCode());
			list.setOrderNum(g.getOrderNo());
			boxOrderLists.add(list);
		}
		return boxOrderLists;
	}

	@RequestMapping("td/courier/login")
	@ResponseBody
	public Map<String, Object> CourierAuth(
			@RequestParam("rfidNum") String rfidNum, HttpSession httpSession) {
		HashMap<String, Object> response = new HashMap<String, Object>();
		if (rfidNum != null && !rfidNum.equals("")) {
			Express express = null;
			Courier courier = courierDao.getCourierInfoByRFID(rfidNum);
			Terminal terminal = (Terminal) httpSession.getAttribute("terminal");
			if (courier != null)express = expressDao.getExpressById(courier.getExpressId());
			if (courier != null && express != null) {
				int across = branchDao.getAcross(terminal.getBranchID());
				if ((express.getPayWay() != 2 && express.getStatus() == 1)
						|| (express.getPayWay() == 0 && express.getPayAlarm() == 2)) {
					response.put("result", "3");
					response.put("expressName", express.getName());
					response.put("errMsg", "owning fee");
				}else if(across==0&&!expenseDao.isExpressAuthed(terminal.getBranchID(),courier.getExpressId())){
					response.put("result", "1");
					response.put("errMsg", "快递未授权");
				} else if(courier.getStatus()==4){
					response.put("result", "4");
					response.put("errMsg", "账号已被禁用，请联系管理员。");
				}else {
					System.out.println("express.getPayAlarm():"
							+ express.getPayAlarm());
//					Terminal terminal = (Terminal) httpSession
//							.getAttribute("terminal");
					ArrayList<Box> boxes = (ArrayList<Box>) boxDao
							.getAvailableBox(terminal);

					if (boxes != null) {
						HashMap<String, Object> payInfo = new HashMap<String, Object>();
						payInfo.put("payWay", express.getPayWay());
						payInfo.put("payBalance", express.getBalance());
						payInfo.put("payAlarm", express.getPayAlarm());
						payInfo.put("companyName", courier.getCourier_company());

						httpSession.setAttribute("courier", courier);
						response.put("result", "0");
						response.put("boxInfo", boxes);
						response.put("payInfo", payInfo);
						response.put("expressName", express.getName());
						response.put("errorRate", courier.getErrorRate());
					} else {
						response.put("result", "2");
						response.put("errMsg", "no box available");
					}

				}

			} else {
//				logger.info("[ERROR]courier invalid");
				response.put("result", "1");
				response.put("errMsg", "courier invalid");
			}

		} else {
//			logger.info("[ERROR]rfid wrong");
			response.put("result", "1");
			response.put("errMsg", "rfid wrong");
		}

		return response;
	}

	@RequestMapping("td/courier/phone")
	@ResponseBody
	public Map<String, Object> CourierAuthByPhone(
			@RequestParam("phoneNum") String phoneNum,
			@RequestParam("passwd") String password, HttpSession httpSession) {
		HashMap<String, Object> response = new HashMap<String, Object>();
		try {
			Express express = null;
			Courier courier = courierDao.getCourierByPhone(phoneNum, password);
			Terminal terminal = (Terminal) httpSession.getAttribute("terminal");
			int across = branchDao.getAcross(terminal.getBranchID());
			if (courier != null)
				express = expressDao.getExpressById(courier.getExpressId());
			if (courier != null && express != null) {
				if (express.getPayWay() != 2 && express.getStatus() == 1) {
					response.put("result", "3");
					response.put("expressName", express.getName());
					response.put("errMsg", "owning fee");
				} else if(across==0&&!expenseDao.isExpressAuthed(terminal.getBranchID(),courier.getExpressId())){
					response.put("result", "1");
					response.put("errMsg", "快递未授权");
				} else if(courier.getStatus()==4){
					response.put("result", "4");
					response.put("errMsg", "账号已被禁用，请联系管理员。");
				}else {

//					Terminal terminal = (Terminal) httpSession
//							.getAttribute("terminal");
					ArrayList<Box> boxes = (ArrayList<Box>) boxDao
							.getAvailableBox(terminal);
					if (boxes != null) {

						HashMap<String, Object> payInfo = new HashMap<String, Object>();
						payInfo.put("payWay", express.getPayWay());
						payInfo.put("payBalance", express.getBalance());
						payInfo.put("payAlarm", express.getPayAlarm());
						payInfo.put("companyName", courier.getCourier_company());

						httpSession.setAttribute("courier", courier);
						response.put("result", "0");
						response.put("boxInfo", boxes);
						response.put("payInfo", payInfo);
						response.put("expressName", express.getName());
						response.put("errorRate", courier.getErrorRate());
					} else {
						response.put("result", "2");
						response.put("errMsg", "no box available");
					}

				}

			} else {
//				logger.info("[ERROR]courier invalid");
				response.put("result", "1");
				response.put("errMsg", "courier invalid");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return response;
	}

	@RequestMapping("td/courier/logout")
	@ResponseBody
	public Map<String, String> CourierLogout(HttpSession httpSession) {
		HashMap<String, String> response = new HashMap<String, String>();
		Courier courier = (Courier) httpSession.getAttribute("courier");
		if (courier == null) {
			response.put("result", "1");
		} else {
			httpSession.removeAttribute("courier");
			response.put("result", "0");
		}
		return response;
	}

	@RequestMapping("td/admin/login")
	@ResponseBody
	public Map<String, String> AdminLogin(@RequestParam("rfidNum") String RFID,
			HttpSession httpSession) {
		HashMap<String, String> response = new HashMap<String, String>();
		if (adminDao.isValid(RFID)) {
			httpSession.setAttribute("admin", "admin");
			response.put("result", "0");
		} else {
			response.put("result", "1");
		}
		return response;
	}

	@RequestMapping("td/admin/logout")
	@ResponseBody
	public Map<String, String> AdminLogout(HttpSession httpSession) {
		HashMap<String, String> response = new HashMap<String, String>();
		String RFID = (String) httpSession.getAttribute("admin");

		if (RFID != null) {
			httpSession.removeAttribute("admin");
			response.put("result", "0");
		} else {
			response.put("result", "1");
		}
		return response;
	}

	@RequestMapping("td/user/login/RFID")
	@ResponseBody
	public synchronized Map<String, String> userRFIDlogin(HttpServletRequest httpRequest,
			HttpServletResponse httpResponse, HttpSession httpSession,
			@RequestParam("rfidNum") String RFID) throws Exception {
		HashMap<String, String> response = new HashMap<String, String>();
		// make sure user exist
		User user = userDao.RFIDValid(RFID);
		if (user != null) {
			Terminal terminal = (Terminal) httpSession.getAttribute("terminal");
			ArrayList<Parcel> parcels = parcelDao.returnParcelInfoByPhoneNum(
					terminal, user);
			// make sure user'parcel exist in certain terminal
			if (parcels != null) {
				user.setCheckCode(parcels.iterator().next().getCheckCode());
				httpSession.setAttribute("user", user);
				httpRequest.getServletContext()
						.getRequestDispatcher("/user/parcels")
						.forward(httpRequest, httpResponse);
			} else {
				response.put("result", "1");
			}// if (parcels != null)
		} else {
			response.put("result", "2");
		}// if (user != null) {
		return response;
	}

	@RequestMapping("td/user/login/checkCode")
	@ResponseBody
	public synchronized Map<String, String> userCheckCodeLogin(
			HttpServletRequest httpRequest, HttpServletResponse httpResponse,
			@RequestParam("checkCode") String checkCode, HttpSession httpSession)
			throws Exception {
		HashMap<String, String> response = new HashMap<String, String>();
		Terminal terminal = (Terminal) httpSession.getAttribute("terminal");
		User user = isValidCheckCode(terminal, checkCode, httpRequest);
		if (user != null) {
			httpSession.setAttribute("user", user);
			httpRequest.getServletContext()
					.getRequestDispatcher("/user/parcels")
					.forward(httpRequest, httpResponse);
		} else {
			response.put("result", "1");
		}

		return response;
	}

	/**
	 * 处理用户退件
	 * 
	 * @param httpRequest
	 * @param httpResponse
	 * @param checkCode
	 * @param parcelNum
	 * @param httpSession
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("td/user/withdrawParcel")
	@ResponseBody
	public Map<String, String> judageWithdrawParcel(
			HttpServletRequest httpRequest, HttpServletResponse httpResponse,
			@RequestParam("checkCode") String checkCode,
			@RequestParam("parcelNum") String parcelNum, HttpSession httpSession)
			throws Exception {
		HashMap<String, String> response = new HashMap<String, String>();
		Terminal terminal = (Terminal) httpSession.getAttribute("terminal");
		Parcel parcel = new Parcel();
		parcel.setCheckCode(checkCode);
		parcel.setParcelNum(parcelNum);
		parcel = parcelDao.withdrawParcel(parcel, terminal);
		if (parcel.getPhoneNum() == null) {
			if (parcelDao.isExtParcelByCheckCodeAndParcelNum(checkCode,
					parcelNum, terminal)) {
				// 取件已经超过三十分钟
				response.put("result", "3");
			} else {
				// 验证码错误
				response.put("result", "2");
			}

		} else {
			int oldBoxSeq = parcelDao.getBoxSeqByParcelID(parcel.getId());
			int boxType = boxDao.getBoxType(oldBoxSeq, terminal);
			int newBoxSeq = boxDao.getBoxSeqByBoxType(boxType, terminal);
			if (newBoxSeq == -1) {
				response.put("result", "1");
			} else {
				boolean dealResult = parcelDao.dealWithdrawParcel(newBoxSeq,
						parcel.getId(), oldBoxSeq);
				// 退件，状态修改为4
				boolean updateBoxStatus = boxDao.boxToggleAvailable(terminal,
						String.valueOf(newBoxSeq), 4);
				System.out.println(String.valueOf(dealResult)
						+ String.valueOf(updateBoxStatus));
				if (dealResult && updateBoxStatus) {
					response.put("result", "0");
					response.put("BoxId", String.valueOf(newBoxSeq));

					String informAdminMsg = "您好！手机号为" + parcel.getPhoneNum()
							+ " 的用户，已经将快递单号为" + parcelNum + "的快件退到"
							+ terminal.getBranch_Short_Addr() + "的邮宝智能快递箱"
							+ terminal.getTerminal_name() + newBoxSeq
							+ "号箱。请及时处理";
					SendSMSHelper
							.send(informAdminMsg, terminal.getAdminPhone(),
									terminal.getSmsPlatform());

				} else {
					response.put("result", "1");
				}
			}

		}
		return response;
	}

	@RequestMapping("td/resendCheckCode")
	@ResponseBody
	public Map<String, String> resendCheckCode(
			@RequestParam("phoneNum") String phoneNum, HttpSession httpSession) {
		String checkCode = null;
		String msg = null;
		HashMap<String, String> response = new HashMap<String, String>();
		Terminal terminal = (Terminal) httpSession.getAttribute("terminal");
		checkCode = parcelDao.getCheckCodeByPhoneNum(phoneNum, terminal);
		if (checkCode == null) {
			Map<String, Object> queryResult = parcelDao
					.getCheckCodeByPhoneNumInBranch(phoneNum, terminal);
			if (queryResult != null) {
				Terminal aimTerminal = terminalDao.get(Integer
						.parseInt(queryResult.get("package_terminal_id")
								.toString()));
				msg = "您的验证码是： " + queryResult.get("package_checkCode")
						+ "，您的包裹在该网点的" + aimTerminal.getTerminal_name() + "。";
			} else {
				response.put("result", "1");
				return response;
			}
		} else {
			msg = "您的验证码是： " + checkCode + "。";
		}

		SendSMSHelper.send(msg, phoneNum, terminal.getSmsPlatform());
		response.put("result", "0");
		return response;
	}

	/**
	 * 检测取货码是否有效
	 * 
	 * @param terminal
	 * @param checkCode
	 * @param httpRequest
	 * @return
	 */
	public User isValidCheckCode(Terminal terminal, String checkCode,
			HttpServletRequest httpRequest) {
		if (httpRequest.getServletContext().getAttribute(
				terminal.getTerminalID() + checkCode) != null) {
			User user = new User();
			user.setMobileNum((String) httpRequest.getServletContext()
					.getAttribute(terminal.getTerminalID() + checkCode));
			user.setCheckCode(checkCode);
			return user;
		} else {
			String phoneNum = parcelDao.isExistParcelByCheckCode(terminal,
					checkCode);
			if (phoneNum != null) {
				User user = new User();
				user.setMobileNum(phoneNum);
				user.setCheckCode(checkCode);
				return user;
			} else {
				return null;
			}
		}
	}

	/**
	 * 快递员注册第一步，发送验证码
	 * 
	 * @param phoneNum
	 * @return 2-快递员已经注册过，转去修改密码
	 */
	@RequestMapping("td/sendCheckCodeToCourier")
	@ResponseBody
	public Map<String, Object> sendCheckCodeToCourier(
			@RequestParam("phoneNum") String phoneNum,
			HttpServletRequest httpRequest, HttpSession httpSession) {
		HashMap<String, Object> response = new HashMap<String, Object>();
		String checkCode = GenerateRandNumHelper.generate(6);
		Terminal terminal = (Terminal) httpSession.getAttribute("terminal");
		if (checkCode != null) {
			String msg = "您的验证码是： " + checkCode;
			SendSMSHelper.send(msg, phoneNum, terminal.getSmsPlatform());
			httpRequest.getServletContext().setAttribute("courier" + checkCode,
					checkCode);
			if (courierDao.isExtCourierByPhoneNum(phoneNum)) {
				// 如果快递员手机号码已经存在数据库
				response.put("result", "2");
			} else {
				response.put("result", "0");
			}

			// 返回所有快递公司，供注册第二部选择使用
			ArrayList<Company> companies = companyDao.getAllCompanys();
			response.put("companies", companies);
		} else {
			response.put("result", "1");
		}
		return response;
	}

	/**
	 * 注册快递员第二部，验证信息，如果正确，注册快递员并返回空箱
	 * 
	 * @param phoneNum
	 * @param checkCode
	 * @param password
	 * @param RFID
	 * @param companyId
	 * @param httpRequest
	 * @param httpSession
	 * @return
	 */
	@RequestMapping("td/registerCourier")
	@ResponseBody
	public HashMap<String, Object> registerCourier(
			@RequestParam("phoneNum") String phoneNum,
			@RequestParam("checkCode") String checkCode,
			@RequestParam("passwd") String password,
			@RequestParam(value = "rfidNum", required = false) String RFID,
			@RequestParam("companyId") int companyId,
			HttpServletRequest httpRequest, HttpSession httpSession) {

		HashMap<String, Object> response = new HashMap<String, Object>();
		// 确认验证码是否有效
		String memCheckCode = (String) httpRequest.getServletContext()
				.getAttribute("courier" + checkCode);
		if (memCheckCode != null) {
			// 创建一个快递员对象
			httpRequest.getServletContext().removeAttribute(
					"courier" + checkCode);
			Courier courier = new Courier();
			courier.setCourier_company(companyDao.getCompanyNameById(companyId));
			courier.setPassword(password);
			courier.setPhoneNum(phoneNum);
			courier.setRFID(RFID);
			boolean resultOfSaveCourier = courierDao
					.saveCourierWithRFID(courier);
			if (resultOfSaveCourier) {
				Terminal terminal = (Terminal) httpSession
						.getAttribute("terminal");
				ArrayList<Box> boxes = (ArrayList<Box>) boxDao
						.getAvailableBox(terminal);
				if (boxes != null) {
					httpSession.setAttribute("courier", courier);
					response.put("result", "0");
					response.put("boxInfo", boxes);
				} else {
					response.put("result", "2");
				}
			} else {
				// 增加快递员失败
				response.put("result", "1");
			}

		} else {
			// 验证失败
			response.put("result", "1");
		}

		return response;

	}

	@RequestMapping("td/resetCourierPassword")
	@ResponseBody
	public HashMap<String, Object> resetCourierPassword(
			@RequestParam("phoneNum") String phoneNum,
			@RequestParam("checkCode") String checkCode,
			@RequestParam("newPasswd") String password,
			@RequestParam(value = "rfidNum", required = false) String RFID,
			HttpServletRequest httpRequest, HttpSession httpSession) {
		HashMap<String, Object> response = new HashMap<String, Object>();
		// 确认验证码是否有效
		String memCheckCode = (String) httpRequest.getServletContext()
				.getAttribute("courier" + checkCode);
		if (memCheckCode != null) {
			// 创建一个快递员对象
			httpRequest.getServletContext().removeAttribute(
					"courier" + checkCode);
			Courier courier = new Courier();
			courier.setPassword(password);
			courier.setPhoneNum(phoneNum);
			courier.setRFID(RFID);
			boolean resultOfSaveCourier = courierDao
					.changeCourierPassword(courier);
			if (resultOfSaveCourier) {
				response.put("result", "0");
			} else {
				// 增加快递员失败
				response.put("result", "1");
			}// if(resultOfSaveCourier){
		} else {
			// 验证失败
			response.put("result", "1");
		}// if(memCheckCode!=null){

		return response;
	}

	/**
	 * 0033 通过开箱码开箱存放/取出物品
	 * 
	 * @param openCode
	 * @param httpSession
	 * @return
	 */
	@RequestMapping("td/courier/openBookedBox")
	@ResponseBody
	public Map<String, String> CourieropenBookedBox(
			@RequestParam("openCode") String openCode, HttpSession httpSession) {
		HashMap<String, String> response = new HashMap<String, String>();
		Terminal terminal = (Terminal) httpSession.getAttribute("terminal");
		Goods openGoods = goodsDao.getboxNumByTerminalIDAndStatusAndOpenCode(
				terminal.getTerminalID(), 0, openCode);
		Goods getGoods = goodsDao.getboxNumByTerminalIDAndStatusAndGetCode(
				terminal.getTerminalID(), 3, openCode);
		if (openGoods == null && getGoods == null) {
			response.put("result", "1");
			response.put("errMsg", "没有对应的预定记录");
		} else {
			if (openGoods != null && getGoods == null) {
				response.put("result", "0");
				response.put("boxSeq", String.valueOf(openGoods.getBoxNum()));
				response.put("orderNo", openGoods.getOrderNo());
				response.put("remark", "0");
			}
			if (getGoods != null && openGoods == null) {
				response.put("result", "0");
				response.put("boxSeq", String.valueOf(getGoods.getBoxNum()));
				response.put("orderNo", getGoods.getOrderNo());
				response.put("remark", "1");
			}

		}
		return response;
	}

	/**
	 * 0034 反馈预定箱格开箱结果
	 * 
	 * @param getCode
	 * @param httpSession
	 * @return
	 */
	@RequestMapping("td/user/login/getCode")
	@ResponseBody
	public Map<String, String> userOpenBookedBox(
			@RequestParam("orderNo") String orderNo,
			@RequestParam("boxStatus") int boxStatus,
			@RequestParam("reqType") String reqType, HttpSession httpSession) {
		HashMap<String, String> response = new HashMap<String, String>();
		Terminal terminal = (Terminal) httpSession.getAttribute("terminal");
		Goods goods = goodsDao.getGoodsByOrderNo(orderNo);
		if (goods == null) {
			response.put("result", "1");
			response.put("errMsg", "没有对应的预定记录");
			return response;
		} else {
			Agent agent = agentDao.getAgentById(goods.getAgentId());
			RequestNotifyThread rnt = new RequestNotifyThread();
			Long timestamp = System.currentTimeMillis() / 1000;

			rnt.setSign(agent.getSign(timestamp));
			rnt.setTimestamp(String.valueOf(timestamp));
			rnt.setOrderNum(goods.getOrderNo());
			rnt.setUrl(agent.getFeedbackUrl());
			rnt.setBoxNum(String.valueOf(goods.getBoxNum()));

			// 反馈我们设备
			// if (boxStatus != 3) {
			// boxDao.boxToggleAvailable(terminal,
			// String.valueOf(goods.getBoxNum()), 2);
			// } else {
			// boxDao.boxToggleAvailable(terminal,
			// String.valueOf(goods.getBoxNum()), 3);
			// }
			if ("0".equals(reqType)) {
				if (goods.getStatus() == 0) {
					rnt.setFuncName("SaveResult");
					String getCode = null;
					if (boxStatus != 3) {
						boxDao.boxToggleAvailable(terminal,
								String.valueOf(goods.getBoxNum()), 2);
					} else {
						boxDao.boxToggleAvailable(terminal,
								String.valueOf(goods.getBoxNum()), 1);
					}
					do {
						getCode = GenerateRandNumHelper.generate(6);
					} while (goodsDao.isExistGetCode(getCode)
							|| goodsDao.isExistOpenCode(getCode));
					rnt.setGetOpenCode(getCode);

					Date now = new Date();
					Timestamp storeTime = new Timestamp(now.getTime());
					goodsDao.updateStatusAndGetCodeByterminalIDAndBoxSeq(
							storeTime, terminal.getTerminalID(),
							goods.getBoxNum(), boxStatus, goods.getOpenCode(),
							getCode);
					rnt.setStatus(String.valueOf(boxStatus));
					Thread thread = new Thread(rnt);
					thread.start();
					response.put("getCode", getCode);// 存物时下发取物码
					response.put("result", "0");
					return response;
				} else {
					response.put("getCode", goods.getGetCode());// 存物时下发取物码
					response.put("result", "0");
					return response;
				}

			} else if ("1".equals(reqType)) {
				if (goods.getStatus() == 3||goods.getStatus() == 8) {
					if ("1".equals(goods.getIsForcedOpen())) {
						rnt.setFuncName("ForcedOpenResult");
					} else {
						rnt.setFuncName("GetResult");
					}
					if (boxStatus == 3) {
						boxDao.boxToggleAvailable(terminal,String.valueOf(goods.getBoxNum()), 0);
						boxDao.setBoxGoods(terminal.getTerminalID(), goods.getBoxNum(), 0);
					} else if (boxStatus == 8){
						goodsDao.updateForcedOpenByOrderNo(orderNo,"0");
					}else {
						boxDao.boxToggleAvailable(terminal,
								String.valueOf(goods.getBoxNum()), 2);
					}
					Date now = new Date();
					Timestamp getTime = new Timestamp(now.getTime());
					if (boxStatus == 3) {
						boxStatus = 4;
					} else if(boxStatus == 8){
						boxStatus = 8;
						getTime = null;
					}else {
						boxStatus = 5;
						getTime = null;
					}
					goodsDao.updateStatusAndGetTimeByterminalIDAndBoxSeq(
							terminal.getTerminalID(), getTime,
							goods.getBoxNum(), boxStatus, goods.getGetCode());
					rnt.setStatus(String.valueOf(boxStatus));
					Thread thread = new Thread(rnt);
					thread.start();
					response.put("result", "0");
					return response;
				} else {
					response.put("result", "0");
					return response;
				}
			} else {
				response.put("result", "1");
				response.put("errMsg", "物品状态错误");
				return response;
			}
		}
	}

	/**
	 * 0035 反馈取消预定箱格结果
	 * 
	 * @return
	 */
	@RequestMapping("td/user/cancelOrder")
	@ResponseBody
	public Map<String, String> CourieropenBookedBox(
			@RequestParam("cancelStatus") int cancelStatus,
			@RequestParam("orderNo") String orderNo, HttpSession httpSession) {
		HashMap<String, String> response = new HashMap<String, String>();
		Goods goods = goodsDao.getGoodsByOrderNo(orderNo);
		if (goods == null) {
			response.put("result", "1");
			response.put("errMsg", "没有对应的预定记录");
		} else {
			Agent agent = agentDao.getAgentById(goods.getAgentId());
			RequestNotifyThread rnt = new RequestNotifyThread();
			Long timestamp = System.currentTimeMillis() / 1000;

			rnt.setSign(agent.getSign(timestamp));
			rnt.setUrl(agent.getFeedbackUrl());
			rnt.setTimestamp(String.valueOf(timestamp));
			rnt.setOrderNum(orderNo);
			rnt.setFuncName("OrderStatusResult");
			if (cancelStatus == 0) {
				if ("3".equals(goods.getRemark())) {
					rnt.setOrderStatus("2");
					goodsDao.updateStatusByOrderNo(orderNo, "7", "3");
				} else {
					rnt.setOrderStatus("0");
					goodsDao.updateStatusByOrderNo(goods.getOrderNo(), "6", "4");
				}
				logger.info("更新箱格状态是否成功----------->"+boxDao.updateBoxStatus(goods.getTerminalId(),goods.getBoxNum(), 0,null));
				logger.info("更新箱格外键是否成功----------->"+boxDao.setBoxGoods(goods.getTerminalId(), goods.getBoxNum(), 0));
			}
			if (cancelStatus == 1) {
				if ("3".equals(goods.getRemark())) {
					rnt.setOrderStatus("3");
				} else {
					rnt.setOrderStatus("1");
				}
			}
			response.put("result", "0");
			Thread thread = new Thread(rnt);
			thread.start();
		}
		return response;
	}
	
	/**
	 * 物检锁检箱格状态上报0036
	 * @param boxSeq
	 * @param boxStatus
	 * @param httpSession
	 * @return
	 * by zgy
	 */
	@RequestMapping("td/box/changeBoxStatus")
	@ResponseBody
	public Map<String, String> changeBoxStatus(
			@RequestParam("boxSeq") String boxSeq,
			@RequestParam("boxStatus") String boxStatus, HttpSession httpSession) {
		HashMap<String, String> response = new HashMap<String, String>();
		Terminal terminal = (Terminal) httpSession.getAttribute("terminal");
		Timestamp timestamp = new Timestamp(new Date().getTime());
		if("0".equals(boxStatus)&&boxDao.queryBoxStatus(terminal, Integer.parseInt(boxSeq))==0){
			if(boxDao.updateBoxStatus(terminal.getTerminalID(), Integer.parseInt(boxSeq), 6,timestamp)){
				response.put("result", "0");
			}else{
				response.put("result", "1");
			}
		}else if(("1".equals(boxStatus)||"4".equals(boxStatus))&&boxDao.queryBoxStatus(terminal, Integer.parseInt(boxSeq))==0){
			if(boxDao.updateBoxStatus(terminal.getTerminalID(), Integer.parseInt(boxSeq), 7,timestamp)){
				boxDao.saveAbnormalBoxLog(terminal.getTerminalID(),boxSeq, 0, "存件异常。", "存件箱格开启失败亦或门检测模块损坏。时间："+TimeHelper.formattingNow());
				response.put("result", "0");
			}else{
				response.put("result", "1");
			}
		}else if("2".equals(boxStatus)&&boxDao.queryBoxStatus(terminal, Integer.parseInt(boxSeq))==1){
			if(boxDao.updateBoxStatus(terminal.getTerminalID(), Integer.parseInt(boxSeq), 8,timestamp)){
				Parcel parcel = parcelDao.queryParcel(terminal.getTerminalID(), Integer.parseInt(boxSeq), 0);
				int logID = parcelDao.saveAbnormalParcelLog(parcel, "0", "2");
				boxDao.saveAbnormalBoxLog(terminal.getTerminalID(),boxSeq, logID, "取件异常", "取件箱格开启失败亦或门检测模块损坏。时间："+TimeHelper.formattingNow());
				response.put("result", "0");
			}else{
				response.put("result", "1");
			}
		}else if("3".equals(boxStatus)&&boxDao.queryBoxStatus(terminal, Integer.parseInt(boxSeq))==6){
			if(boxDao.updateBoxStatus(terminal.getTerminalID(), Integer.parseInt(boxSeq), 0,null)){
				response.put("result", "0");
			}else{
				response.put("result", "1");
			}
		}else if("5".equals(boxStatus)&&boxDao.queryBoxStatus(terminal, Integer.parseInt(boxSeq))==8){
			if(boxDao.updateBoxStatus(terminal.getTerminalID(), Integer.parseInt(boxSeq), 1,null)){
				response.put("result", "0");
			}else{
				response.put("result", "1");
			}
		}else{
			response.put("result", "1");
		}
		return response;
	}
	
	/**
	 * 设备异常警报接口0037
	 * @param a
	 * @param b
	 * @param c
	 * @param httpSession
	 * @return
	 * by zgy
	 */
	@RequestMapping("td/abnormal/alarming")
	@ResponseBody
	public Map<String, String> abnormalAlarming(
			@RequestParam("tosend") String a,
			@RequestParam("detectInterval") String b,
			@RequestParam("detectTimes") String c, HttpSession httpSession) {
		HashMap<String, String> response = new HashMap<String, String>();
		Terminal terminal = (Terminal) httpSession.getAttribute("terminal");
		try{
			int tosend = Integer.parseInt(a);
			int detectTimes = Integer.parseInt(c);
			terminal = terminalDao.get(terminal.getTerminalID());
			if(tosend>0&&detectTimes>=3&&(terminal.getAbnormalTime()==null||TimeHelper.isNowLate(terminal.getAbnormalTime(), 30))){
				SendSMSHelper.send("懒猫 "+terminal.getBranch_Short_Addr()+"设备，请求数维持在"+tosend+"。", terminalDao.getAlarmPhone("alarmPhoneNum"), 1);
			}
			terminalDao.updateTosend(terminal.getTerminalID(),tosend,new Timestamp(new Date().getTime()));
			response.put("result", "0");
		}catch(Exception e){
			response.put("result", "1");
			response.put("error", "参数非法");
		}
		return response;
	}
}
